package com.stoken.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.hibernate.classic.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.stoken.dao.AchievementListDao;
import com.stoken.dao.LineUseDao;
import com.stoken.dao.MemberBaseInfoDao;
import com.stoken.dao.MemberRegisterInfoDao;
import com.stoken.dao.MemberShopWalletDao;
import com.stoken.domain.AchievementList;
import com.stoken.domain.LineUse;
import com.stoken.domain.MemberAchievement;
import com.stoken.domain.MemberActiveList;
import com.stoken.domain.MemberBaseInfo;
import com.stoken.domain.MemberRegisterInfo;
import com.stoken.domain.MemberShopWallet;
import com.stoken.domain.MemberWallet;
import com.stoken.service.BonusCalculationService;
import com.stoken.service.MemberAchievementService;
import com.stoken.service.MemberActiveListService;
import com.stoken.service.MemberBaseInfoService;
import com.stoken.service.MemberRegisterInfoService;
import com.stoken.service.MemberWalletService;
import com.stoken.web.StokenUtils;
import com.stoken.web.control.vo.Message;
import com.symbio.dao.hibernate.GenericDaoImpl;
import com.symbio.service.impl.AbstractServiceImpl;

@Service
public class MemberBaseInfoServiceImpl extends AbstractServiceImpl<MemberBaseInfo, Long> implements MemberBaseInfoService{
	
    @Autowired
	private MemberBaseInfoDao memberBaseInfoDao;
    
    @Autowired
	private MemberRegisterInfoDao memberRegisterInfoDao;
    
    @Autowired
    private MemberRegisterInfoService memberRegisterInfoService;
    
    @Autowired
    private AchievementListDao achievementListDao;
    
    @Autowired
    private MemberShopWalletDao memberShopWalletDao;
    
    @Autowired
    private LineUseDao lineUseDao;
    
	/**
	 * 电子钱包服务层
	 */
	@Autowired
	private MemberWalletService memberWalletService;
	
	@Autowired
	private MemberActiveListService memberActiveListService;
	
	@Autowired
	private MemberAchievementService memberAchievementService;
	
	@Autowired
	private BonusCalculationService bonusCaculationService;

	@Override
	public GenericDaoImpl<MemberBaseInfo, Long> getDao() {
		return memberBaseInfoDao;
	}

	@Override
	public void updateMBI(MemberBaseInfo mbi) {
		memberBaseInfoDao.update(mbi);
		
	}

	@Override
	public void updatePhone(String phone, Long mid) {
		MemberBaseInfo mbInfo = memberBaseInfoDao.find(mid);
		mbInfo.setBasePhone(phone);
		memberBaseInfoDao.update(mbInfo);	
	}

	@Override
	public void updateFPassword(long id, String fPassword) {
		MemberBaseInfo mbi = this.get(id);
		if(mbi != null)
		{
			mbi.setBasePasswordFirst(fPassword);
			memberBaseInfoDao.update(mbi);
		}
		
	}

	@Override
	public void updateSPassword(long id, String sPassword) {
		MemberBaseInfo mbi = this.get(id);
		if(mbi != null)
		{
			mbi.setBasePasswordSeconde(sPassword);
			memberBaseInfoDao.update(mbi);
		}
	}

	@Override
	public void updateTPassword(long id, String tPassword) {
		MemberBaseInfo mbi = this.get(id);
		if(mbi != null)
		{
			mbi.setBasePasswordThird(tPassword);
			memberBaseInfoDao.update(mbi);
		}
		
	}

	@Override
	public boolean findSercondP(long id, String sPassword) {
		Object[] obj = new Object[]{id,sPassword};
		String hql = "from MemberBaseInfo where id = ? and basePasswordSeconde = ?";
		MemberBaseInfo mbi = memberBaseInfoDao.find(hql , obj);
		if(mbi != null)
		{
			return true;
		}	
		return false;	
	}

	@Override
	public void saveRegisterInfo(MemberRegisterInfo registerInfo,
			MemberBaseInfo baseInfo) {
		Session session = memberBaseInfoDao.getSessionFactory().getCurrentSession();
		session.save(registerInfo);
		session.save(baseInfo);
		
	}

	@Override
	public MemberBaseInfo findBaseByUserName(String hql, String baseUsername) {
	
		return memberBaseInfoDao.find(hql, new Object[]{baseUsername});
		
	}

	@Override
	public MemberBaseInfo verificationLogin(String account, String password) {
		Object[] obj = new Object[]{account};
		String hql = "from MemberBaseInfo where baseUsername = ?";
		MemberBaseInfo memBerBaseInfo = memberBaseInfoDao.find(hql , obj);
		//MemberBaseInfo memBerBaseInfo = memberBaseInfoDao.find("baseUsername", account);
		if(memBerBaseInfo != null){
			MemberRegisterInfo memberRegisInfo = memberRegisterInfoDao.find("baseUsername", account);
			if(memBerBaseInfo.getBasePasswordFirst().equals(password) && memberRegisInfo.getRegisterAvtivestate() == 1){
				return memBerBaseInfo;
			}			
		}
		return null;
	}

	@Override
	public Message updateActiveMember(String userAccount, String activeName,
			String grade) {
		MemberBaseInfo memberBaseInfo = findBaseByUserName("from MemberBaseInfo where baseUsername = ?",userAccount);
		MemberBaseInfo aBaseInfo = findBaseByUserName("from MemberBaseInfo where baseUsername = ?",activeName);
		MemberWallet memberWallet = memberWalletService.findWalletByUsername(userAccount);
//		MemberWallet activeWallet = memberWalletService.findWalletByUsername(activeName);
		
		if(memberWallet == null)
		{
			return new Message(0,"电子钱包为空");
		}
//		if(activeWallet == null)
//		{
//			return new Message(0,"注册电子钱包为空");
//		}
		double registerMoney = StokenUtils.COPPERMONEY;
		//**
		if(StringUtils.equals(grade, "1"))
		{
			registerMoney = StokenUtils.COPPERMONEY;
		}
		else if(StringUtils.equals(grade, "2"))
		{
			registerMoney = StokenUtils.SILVERMONEY;
		}
		else if(StringUtils.equals(grade, "5"))
		{
			registerMoney = StokenUtils.GOLDENMONEY;
		}
		else if(StringUtils.equals(grade, "10"))
		{
			registerMoney = StokenUtils.VIPMONEY;
		}
		else if(StringUtils.equals(grade, "30"))
		{
			registerMoney = StokenUtils.MASONRYMONEY;
		}
		
		double money = memberWallet.getWalletRemain();
		if(money - registerMoney < 0)
		{
			return new Message(0,"电子钱包余额不足");
		}
		MemberRegisterInfo register = memberRegisterInfoService.findRegisterByUserName(activeName);
		if(register==null)
		{
			return new Message(0,"注册用户不存在");
		}
		if(register.getRegisterAvtivestate()==1){
			return new Message(0,"该用户已被激活");
		}
		
		//激活注册状态
		register.setRegisterGrade(new Integer(grade));
		register.setRegisterActivetime(new Date());
		register.setRegisterAvtivestate(1);
		memberRegisterInfoService.update(register);
		
		//减少电子钱包金额
		memberWallet.setWalletRemain(memberWallet.getWalletRemain()-registerMoney);
		memberWalletService.update(memberWallet);
		
		//注册电子钱包金额
//		activeWallet.setWalletRemain(registerMoney);
//		memberWalletService.update(activeWallet);
		
		//添加电子钱包明细
		MemberActiveList entity = new MemberActiveList();
		entity.setActiveName(aBaseInfo.getBaseName());
		entity.setActiveTime(new Date());
		entity.setActiveType(new Integer(grade));
		entity.setActiveUsername(register.getBaseUsername());
		entity.setBaseUsername(memberBaseInfo);
		entity.setWalletRemain(memberWallet.getWalletRemain()-registerMoney);
		memberActiveListService.save(entity);
		
		//添加会员业绩表
		MemberAchievement achievement = new MemberAchievement();
		achievement.setBaseUsername(aBaseInfo);
		achievement.setRegisterGrade(new Integer(grade));
		memberAchievementService.save(achievement);
		
		//添加会员奖金明细记录
		AchievementList achievmentList = new AchievementList(register);
		achievementListDao.save(achievmentList);
		
		//添加线路信息
		LineUse lineUse  = new LineUse();		
	    if(StringUtils.equals(grade, "1")){
		  lineUse.setCanUseOther(2);
		  lineUse.setCanUseOws(0);
	    }else if(StringUtils.equals(grade, "2")){
		  lineUse.setCanUseOther(8);
		  lineUse.setCanUseOws(0);
	    }else if(StringUtils.equals(grade, "5")){
		  lineUse.setCanUseOther(30);
		  lineUse.setCanUseOws(0);
	    }else if(StringUtils.equals(grade, "10")){
		  lineUse.setCanUseOther(100);
		  lineUse.setCanUseOws(0);
	    }else if(StringUtils.equals(grade, "30")){
		  lineUse.setCanUseOther(100);
		  lineUse.setCanUseOws(0);
	     }
	    lineUse.setBaseUsername(aBaseInfo);
		lineUseDao.save(lineUse);
		
		//添加电子钱包
		MemberWallet activeWallet = new MemberWallet();
		activeWallet.setBaseUsername(aBaseInfo);
		activeWallet.setWalletRemain(0);
		memberWalletService.save(activeWallet);
		//添加消费积分表
		MemberShopWallet memberShopWallet = new MemberShopWallet();
		memberShopWallet.setBaseUsername(aBaseInfo);
		memberShopWallet.setShopWalletBalance(0);
		memberShopWallet.setShopWalletLastTime(new Date());
		memberShopWalletDao.save(memberShopWallet);
		
		//计算直接推荐奖金
		bonusCaculationService.calculateSellBonus(register);
		
		return new Message(1,"");
	}

	@Override
	public List<MemberRegisterInfo> findServerList(String username,String firstLevel) {
		String hql1 = "from MemberRegisterInfo where baseUsername = ?";
		MemberRegisterInfo reg = memberRegisterInfoDao.find(hql1 , new Object[]{username});
		if(reg == null){
			//return new Message(0,"销售人员不存在！");
		}
		String level = reg.getRegisterLevel();
		String[] levels = level.split("-");
		int[] uls = new int[]{new Integer(levels[0]),new Integer(levels[1])};
		List<String> list = new ArrayList<String>();
		list.add(level);
		for (int i = 1; i < 4; i++) {
			int minG = (2<<(i-1))*(uls[1]-1)+1;
			int maxG = (2<<(i-1))*uls[1];
			for (int j = 0; j <= maxG - minG; j++) {
				list.add((uls[0]+i)+"-"+(minG+j));
			}
		}
		String hql2 = "from MemberRegisterInfo where registerLevel in (";
		for (int i = 0; i < list.size(); i++) {
			if(i==list.size()-1)
			{
				hql2 += "'"+list.get(i)+"'";				
			}else{
				hql2 += "'"+list.get(i)+"',";
			}
		}   
		hql2 +=	")";
		List<MemberRegisterInfo> registerList = memberRegisterInfoDao.findList(hql2, new Object[]{});
		
		//memberRegisterInfoDao.getSessionFactory().getCurrentSession().clear();
		
		String[] fl = firstLevel.split("-");
		int[] fls = new int[]{new Integer(fl[0]),new Integer(fl[1])};
		List<String> fList = new ArrayList<String>();
		fList.add(firstLevel);
		for (int i = 1; i < 4; i++) {
			int minG = (2<<(i-1))*(fls[1]-1)+1;
			int maxG = (2<<(i-1))*fls[1];
			for (int j = 0; j <= maxG - minG; j++) {
				fList.add((fls[0]+i)+"-"+(minG+j));
			}
		}
		List<MemberRegisterInfo> showList = new ArrayList<MemberRegisterInfo>();
		List<String> tempList = new ArrayList<String>();
		for (int i = 0; i < fList.size(); i++) {
			boolean boo = true;
			String ls = list.get(i);
			for (MemberRegisterInfo mri : registerList) {
				if(StringUtils.equals(mri.getRegisterLevel(), ls)){
					mri.setShowLevel(fList.get(i));
					mri.setUse(false);
					showList.add(mri);
					tempList.add(ls);
					boo = false;
					break;
				}
			}
			if(boo)
			{
				String[] l = ls.split("-");
				String pLeve = (new Integer(l[0])-1)+"-"+((new Integer(l[1])+1)/2);
				MemberRegisterInfo m = new MemberRegisterInfo();
				m.setShowLevel(fList.get(i));
				if(tempList.contains(pLeve)){
					for (MemberRegisterInfo mri : showList) {
						if(StringUtils.equals(mri.getRegisterLevel(), pLeve)){
							m.setTempUsername(mri.getBaseUsername());
							break;
						}
					}
					m.setUse(true);
				}
				showList.add(m);
			}

		}
		
		for (MemberRegisterInfo memberRegisterInfo : showList) {
			
		}
		
		return showList;
	}
    
	
	public static void main(String[] args) {
		String level = "2-2";
		String[] levels = level.split("-");
		int[] uls = new int[]{new Integer(levels[0]),new Integer(levels[1])};
		List<String> list = new ArrayList<String>();
		list.add(level);
		for (int i = 1; i < 4; i++) {
			int minG = (2<<(i-1))*(uls[1]-1)+1;
			int maxG = (2<<(i-1))*uls[1];
			for (int j = 0; j <= maxG - minG; j++) {
				list.add((uls[0]+i)+"-"+(minG+j));
			}
		}
		for (String string : list) {
			
		}
		
	
	}

	@Override
	public MemberBaseInfo getMemberBaseInfoByAccount(String account) {
		
		return memberBaseInfoDao.find("baseUsername",account);
	}


}
